package com.lhz.framework.server;

import com.lhz.framework.aspect.http.HttpLog;
import jakarta.annotation.Resource;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Author: LiHuaZhi
 * @Date: 2021/6/12 23:50
 * @Description:
 **/
@Component
public class RestServer {
    @Resource
    private RestTemplate restTemplate;

    /**
     * 单个对象
     *
     * @param url
     * @param token
     * @param method
     * @param obj
     * @return
     */
    @HttpLog(urlIndex = 1, reqParamIndex = 3, reqTypeIndex = 4)
    public Map<String, Object> doHttp(String url, String token, HttpMethod method, Object obj) {
        HttpHeaders headers = new HttpHeaders();
        //token根据需求来订
        headers.add("Authorization", token);
        headers.setContentType(MediaType.APPLICATION_JSON);
        //类型可以设置为参数形式
        //headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity entity = new HttpEntity(obj, headers);
        //将obj写道body中
        ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<>() {
        };
        ResponseEntity<Map<String, Object>> exchange = restTemplate.exchange(url, method, entity, responseType);
        return exchange.getBody();
    }
}
